import errorLogger from '../../utils/error-logger';

Page({
  data: {
    logs: [],
    loading: true
  },
  
  onLoad() {
    this.loadErrorLogs();
  },
  
  onPullDownRefresh() {
    this.loadErrorLogs();
    wx.stopPullDownRefresh();
  },
  
  // 模拟从本地存储加载错误日志
  loadErrorLogs() {
    this.setData({ loading: true });
    
    // 模拟从存储中加载日志
    setTimeout(() => {
      try {
        // 在实际应用中，这里应该从本地存储或服务器获取日志
        // 这里我们模拟一些日志数据
        const mockLogs = this.generateMockLogs();
        
        this.setData({
          logs: mockLogs,
          loading: false
        });
      } catch (error) {
        console.error('加载错误日志失败', error);
        this.setData({
          logs: [],
          loading: false
        });
        
        wx.showToast({
          title: '加载日志失败',
          icon: 'none'
        });
      }
    }, 500);
  },
  
  // 生成模拟日志数据
  generateMockLogs() {
    const types = ['js', 'api', 'network', 'promise', 'custom'];
    const pages = ['index', 'logs', 'error-test'];
    const errorMessages = [
      'TypeError: Cannot read property of undefined',
      'Failed to fetch API data',
      'Network request timeout',
      'Promise rejection unhandled',
      'Custom business logic error',
      'Invalid user input'
    ];
    
    const logs = [];
    
    // 生成10-20条随机日志
    const count = Math.floor(Math.random() * 10) + 10;
    
    for (let i = 0; i < count; i++) {
      const type = types[Math.floor(Math.random() * types.length)];
      const page = pages[Math.floor(Math.random() * pages.length)];
      const message = errorMessages[Math.floor(Math.random() * errorMessages.length)];
      const timestamp = Date.now() - Math.floor(Math.random() * 86400000); // 随机时间，最长1天前
      
      logs.push({
        id: `log_${i}_${Date.now()}`,
        type,
        message,
        page,
        timestamp,
        formatted_time: new Date(timestamp).toLocaleString()
      });
    }
    
    // 按时间倒序排列
    return logs.sort((a, b) => b.timestamp - a.timestamp);
  },
  
  // 查看日志详情
  viewLogDetail(e) {
    const { index } = e.currentTarget.dataset;
    const log = this.data.logs[index];
    
    wx.showModal({
      title: '错误日志详情',
      content: JSON.stringify(log, null, 2),
      showCancel: false,
      confirmText: '关闭'
    });
  },
  
  // 清除所有日志
  clearAllLogs() {
    wx.showModal({
      title: '确认清除',
      content: '是否清除所有错误日志？此操作不可恢复。',
      success: (res) => {
        if (res.confirm) {
          // 清除内存中的日志
          errorLogger.clearLogs();
          
          // 清除UI显示
          this.setData({
            logs: []
          });
          
          wx.showToast({
            title: '日志已清除',
            icon: 'success'
          });
        }
      }
    });
  }
}); 